#!/bin/bash

# MCP Server Startup Script with Memory Configuration
# Automatically reads memory settings from config/server.json

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🚀 Starting MCP Java Decompiler Server${NC}"
echo -e "${BLUE}======================================${NC}"

# Check if config file exists
CONFIG_FILE="config/server.json"
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo -e "${RED}❌ Configuration file not found: $CONFIG_FILE${NC}"
    echo -e "${YELLOW}💡 Please ensure config/server.json exists${NC}"
    exit 1
fi

# Extract memory configuration from JSON
MAX_OLD_SPACE_SIZE=$(node -e "
try {
  const config = require('./config/server.json');
  console.log(config.server?.memory?.maxOldSpaceSize || 4096);
} catch (error) {
  console.log(4096);
}")

ENABLE_GC=$(node -e "
try {
  const config = require('./config/server.json');
  console.log(config.server?.memory?.enableGC !== false ? 'true' : 'false');
} catch (error) {
  console.log('true');
}")

AUTO_OPTIMIZE=$(node -e "
try {
  const config = require('./config/server.json');
  console.log(config.server?.memory?.autoOptimizeForLargeRepository !== false ? 'true' : 'false');
} catch (error) {
  console.log('true');
}")

# Build NODE_OPTIONS
NODE_OPTIONS="--max-old-space-size=${MAX_OLD_SPACE_SIZE}"

if [[ "$ENABLE_GC" == "true" ]]; then
    NODE_OPTIONS="$NODE_OPTIONS --expose-gc"
fi

# Note: --optimize-for-size is not allowed in NODE_OPTIONS, skip it

# Display configuration
echo -e "${GREEN}📋 Memory Configuration:${NC}"
echo -e "   💾 Max Memory: ${MAX_OLD_SPACE_SIZE}MB"
echo -e "   🗑️  GC Enabled: ${ENABLE_GC}"
echo -e "   ⚡ Auto Optimize: ${AUTO_OPTIMIZE}"
echo -e "   🔧 NODE_OPTIONS: ${NODE_OPTIONS}"
echo ""

# Check if build is needed
if [[ ! -d "dist" ]] || [[ "src" -nt "dist" ]]; then
    echo -e "${YELLOW}🔨 Building TypeScript...${NC}"
    npm run build
    echo -e "${GREEN}✅ Build completed${NC}"
    echo ""
fi

# Determine which server to start
SERVER_TYPE=${1:-"stdio"}
case "$SERVER_TYPE" in
    "stdio"|"local")
        echo -e "${BLUE}🎯 Starting Local MCP Server (stdio)${NC}"
        export NODE_OPTIONS="$NODE_OPTIONS"
        exec node dist/index.js
        ;;
    "http"|"web")
        echo -e "${BLUE}🌐 Starting HTTP MCP Server${NC}"
        export NODE_OPTIONS="$NODE_OPTIONS"
        exec node dist/mcp-http-server.js
        ;;
    *)
        echo -e "${RED}❌ Invalid server type: $SERVER_TYPE${NC}"
        echo -e "${YELLOW}Usage: $0 [stdio|local|http|web]${NC}"
        echo ""
        echo -e "${YELLOW}Examples:${NC}"
        echo -e "  $0              # Start local MCP server (default)"
        echo -e "  $0 stdio        # Start local MCP server"
        echo -e "  $0 http         # Start HTTP MCP server"
        exit 1
        ;;
esac